package org.ycy.data.generator.sink;

import cn.hutool.core.io.FileUtil;
import org.ycy.data.generator.constants.Symbol;
import org.ycy.data.generator.entity.TemplateConfig;
import org.ycy.data.generator.utils.SqlUtils;

import java.nio.charset.Charset;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: data-generator
 * @ClassName SqlSink
 * @description:
 * @author: ycy
 * @create: 2023-06-16 22:46
 * @Version 1.0
 **/
public class SqlSink extends Sink {

    public SqlSink(TemplateConfig templateConfig) {
        super(templateConfig);
    }

    @Override
    public String createHeader() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("insert into ");
        stringBuilder.append(templateConfig.getName());
        stringBuilder.append(" ( ");
        String columnJoin = templateConfig.getColumns().stream().map(item -> item.getColumnCode()).collect(Collectors.joining(Symbol.COMMA));
        stringBuilder.append(columnJoin);
        stringBuilder.append(" ) values ");
        headers = stringBuilder.toString();
        return headers;
    }


    @Override
    public void append(List<List<Object>> data) {

        List<String> lines = data.stream().map(item ->
                        item.stream().map(cl -> SqlUtils.wrapField(cl)).collect(Collectors.joining(Symbol.COMMA)))
                .map(item -> headers + " ( " + item + " ) ; ").collect(Collectors.toList());
        FileUtil.appendLines(lines, file, Charset.defaultCharset());
        data.clear();
        //TODO
    }

    @Override
    public void close() {
        //TODO
    }
}